import React, { useRef } from "react";
import { View, StyleSheet, FlatList, RefreshControl } from "react-native";
import { Stack } from "expo-router";
import { router } from "expo-router";
import { useTheme } from "@/contexts/ThemeContext";
import { getHeaderStyle } from "@/styles/header.style";
import AlertComponent from "@/components/Global/Alert";
import { AlertRefType } from "@/components/Global/Alert/types";
import { SourceType } from "@/types/contact";
import { Ionicons } from "@expo/vector-icons";
import RequestItem from "./components/RequestItem";
import EmptyState from "@/components/Global/EmptyState";
import ErrorState from "./components/ErrorState";
import { useFriendRequests } from "./hooks/useFriendRequests";

interface FriendApplyListProps {
  useMockData?: boolean;
}

// 主组件
const FriendApplyList: React.FC<FriendApplyListProps> = ({
  useMockData = true,
}) => {
  const { colors, themeMode } = useTheme();
  const headerStyles = getHeaderStyle(themeMode);
  const alertRef = useRef<AlertRefType>(null);

  const {
    requests,
    loading,
    refreshing,
    error,
    fetchRequests,
    handleRefresh,
    handleAccept,
    handleReject,
  } = useFriendRequests({ alertRef, useMockData });

  // 处理点击申请项
  const handleItemPress = (item) => {
    router.push(`/userprofile/${item.fromId}/?type=${SourceType.ID}`);
  };

  const renderContent = () => {
    if (loading && !refreshing) {
      return (
        <View style={styles.loadingContainer}>
          <EmptyState
            icon={
              <Ionicons
                name="hourglass-outline"
                size={60}
                color={colors.text.secondary}
              />
            }
            title="加载中..."
          />
        </View>
      );
    }

    if (error) {
      return <ErrorState message={error} onRetry={fetchRequests} />;
    }

    return (
      <FlatList
        data={requests}
        renderItem={({ item }) => (
          <RequestItem
            item={item}
            onAccept={handleAccept}
            onReject={handleReject}
            onPress={handleItemPress}
          />
        )}
        keyExtractor={(item) => item.id}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={handleRefresh}
            colors={[colors.primary]}
            tintColor={colors.primary}
          />
        }
        ListEmptyComponent={
          !loading && (
            <EmptyState
              icon={
                <Ionicons
                  name="people-outline"
                  size={60}
                  color={colors.text.secondary}
                />
              }
              title="暂无好友申请"
            />
          )
        }
        contentContainerStyle={{ flexGrow: 1 }}
      />
    );
  };

  return (
    <>
      <Stack.Screen
        options={{
          title: "好友申请",
          headerTitleAlign: headerStyles.headerTitleAlign as "left" | "center",
          headerStyle: headerStyles.headerStyle,
          headerTintColor: headerStyles.headerTintColor,
          headerTitleStyle: headerStyles.headerTitleStyle,
        }}
      />
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <AlertComponent
          ref={alertRef}
          duration={2000}
          style={styles.alertContainer}
        />
        {renderContent()}
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  alertContainer: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    zIndex: 9999,
    margin: 20,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default FriendApplyList;
 